package site.yunnong.atvris.portal.util;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import site.yunnong.atvris.dao.domain.Banner;
import site.yunnong.atvris.dao.domain.Video;
import site.yunnong.atvris.dao.domain.VideoExample;
import site.yunnong.atvris.dao.mapper.VideoMapper;
import site.yunnong.atvris.service.BannerService;
import site.yunnong.atvris.common.enumeration.BannerStatusEnum;
import site.yunnong.atvris.common.enumeration.BannerTypeEnum;

import javax.annotation.Resource;
import java.util.List;
import java.util.Random;

/**
 * 用来从所有视频中随机抽取几条
 *  作为广告插入广告数据库
 * @author zjh
 * @date 2021/8/31 17:27
 */
//@Component
@Slf4j
public class FixAdAndRecUtil implements InitializingBean {
    
    @Resource
    private VideoMapper videoMapper;
    @Resource
    private BannerService bannerService;
    
    @Override
    public void afterPropertiesSet() throws Exception {
        log.info("start fix ad...");
        List<Video> videos = videoMapper.selectByExample(new VideoExample());
        List<Integer> indexes = Lists.newArrayList();
        // 随机抽100个视频作为推送广告
        for (int i = 0; i < 100; i ++) {
            int index = new Random().nextInt(videos.size() - 1) ;
            while(indexes.contains(index)) {
                index = new Random().nextInt(videos.size() - 1) ;
            }
            indexes.add(index);
        }
        for (Integer index : indexes) {
            Video video = videos.get(index);
            log.info("fix ad, id: {}", video.getId());
            // banner
            Banner banner = Banner.builder().type(BannerTypeEnum.INNER_VIDEO.getValue()).relativeId(video.getId())
                    .link("")
                    .cover(video.getCover())
                    .title(video.getTitle())
                    .status(BannerStatusEnum.ACTIVE.getValue())
                    .build();
            bannerService.insertSelective(banner);
            log.info("fix ad, id: {}, SUCCESS", video.getId());
        }
        log.info("fix ad finished...");
    }
}
